package cn.fintecher.pangolin.service.business.scheduled;

import cn.fintecher.pangolin.common.enums.BaseSelect;
import cn.fintecher.pangolin.common.enums.HistoryCaseStatus;
import cn.fintecher.pangolin.common.utils.BeanUtils;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.BaseCase;
import cn.fintecher.pangolin.entity.elastic.HistoryCases;
import cn.fintecher.pangolin.service.business.repository.elasticsearch.BaseCaseRespository;
import cn.fintecher.pangolin.service.business.repository.elasticsearch.HistoryCasesRespository;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wangxiangdong
 * @Description 待分配案件到期执行自动退案操作
 * @Date 2019/10/29 14:45
 **/
@Component
@EnableScheduling
@Slf4j
public class RetireWaitCaseScheduled {

    @Autowired
    private BaseCaseRespository baseCaseRespository;

    @Autowired
    private HistoryCasesRespository historyCasesRespository;

    @Scheduled(cron = "10 0 0 * * ?")
    void retireCase() {
        log.info("待分配系统自动退案调度任务开始:{}", ZWDateUtil.getFormatNowDateTime("yyyy-MM-dd HH:mm:ss"));
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("isDistribute.keyword",BaseSelect.NO.name()))
                .must(QueryBuilders.rangeQuery("endCaseDate").lt(ZWDateUtil.getNowDate().getTime()));
        List<BaseCase> baseCaseList = Lists.newArrayList(baseCaseRespository.search(boolQueryBuilder));
        if (baseCaseList.size() == 0) {
            log.info("待分配系统自动退案调度任务结束，没有退案的案件:{}", ZWDateUtil.getFormatNowDateTime("yyyy-MM-dd HH:mm:ss"));
            return;
        }
        List<List<BaseCase>> partBaseCase = Lists.partition(baseCaseList, 10000);
        for (List<BaseCase> part : partBaseCase) {
            List<HistoryCases> historyCasesArrayList = new ArrayList<>();
            for (BaseCase baseCase : part) {
                HistoryCases historyCases = new HistoryCases();
                BeanUtils.copyPropertiesIgnoreNull(baseCase, historyCases);
                historyCases.setHistoryCaseStatus(HistoryCaseStatus.RETIRE_POOL);
                historyCases.setOperateTime(ZWDateUtil.getNowDateTime());
                historyCasesArrayList.add(historyCases);
            }
            baseCaseRespository.deleteAll(part);
            historyCasesRespository.saveAll(historyCasesArrayList);
        }
        log.info("待分配系统自动退案调度任务结束:{}", ZWDateUtil.getFormatNowDateTime("yyyy-MM-dd HH:mm:ss"));
    }

}
